<route lang="json5" type="page">
{
	style: {
		navigationStyle: 'custom',
		navigationBarTitleText: '排行榜',
	},
}
</route>

<template>
	<view class="page-exercise">
		<fly-navbar
			backgroundColor="transparent"
			:leftText="paperDetailsInfo?.paper_name || '练习题'"
			textColor="#ffffff"
			fixed
		/>
		<image
			class="w-full h-full fixed top-0 left-0 z-1"
			:src="baseImg + '/book/book-exercise-bg.jpg'"
		></image>
		<view
			class="w-full h-[100vh] absolute top-0 left-0 z-2 box-border"
			:style="{ paddingTop: barAlbright + 'rpx' }"
		>
			<scroll-view
				scroll-y
				class="w-full h-full box-border"
				v-if="paperDetailsInfo && pageInfo.thisPage === 1"
			>
				<view class="w-full pt-[207rpx] pb-[65rpx] px-[34rpx] box-border">
					<view
						class="w-full bg-white relative min-h-[400rpx] rounded-[33rpx] flex flex-col items-center paper-item px-[35rpx] pb-[46rpx] box-border"
					>
						<view class="top-[35rpx] right-[35rpx] absolute text-[#34A4E2] text-[31rpx]"
							>用时:
							<text class="text-[#303030] inline-block w-[60rpx]">{{
								formatTime(answerTime, 'm:s')
							}}</text></view
						>
						<image
							class="w-[170rpx] h-[211rpx] rounded-[25rpx] -mt-[85rpx] border-1 border-solid border-[#fff] paper-image"
							:src="paperDetailsInfo.book_cover_img"
						></image>
						<view class="w-full pt-[27rpx]">
							<book-paper
								:list="paperDetailsInfo.qtrunk"
								:current="current"
								@getAnswer="getAnswer"
							></book-paper>
							<view
								:class="[
									'w-full',
									'grid',
									current <= 1 ? 'grid-cols-1' : 'grid-cols-2 gap-x-[26rpx]',
									'mt-[87rpx]',
								]"
							>
								<view
									class="w-full h-[111rpx] rounded-[55rpx] flex justify-center items-center text-[#303030] text-[32rpx]"
									style="background: #f0f1f3"
									@tap="prev"
									v-if="current > 1"
									>上一题</view
								>
								<view
									class="w-full h-[111rpx] rounded-[55rpx] flex justify-center items-center text-[#fff] text-[32rpx]"
									style="background: #3aa2e4"
									@tap="next"
									v-if="current < paperDetailsInfo.qtrunk.length"
									>下一题</view
								>
								<view
									class="w-full h-[111rpx] rounded-[55rpx] flex justify-center items-center text-[#fff] text-[32rpx]"
									style="background: #3aa2e4"
									@tap="submit"
									v-if="current === paperDetailsInfo.qtrunk.length"
									>提交</view
								>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<no-page
				v-if="pageInfo.thisPage === 0"
				height="100%"
				:type="pageInfo.type"
				:title="pageInfo.title"
				:btnTitle="pageInfo.btnTitle"
				@click="retry"
			></no-page>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { storeToRefs } from 'pinia';
import { systemInfo } from '@/utils/getSystemInfo';
import { formatTime } from '@/utils';
import { useUserStore } from '@/store';
import { toAuthPage } from '@/utils/jump';
import { getPaperInfo, commitPaperInfo } from '@/service/book';
import onShare from '@/hooks/useShare';
import BookPaper from '../components/book-paper.vue';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { onShareAppMessage, onShareTimeline } = onShare();
const baseImg = ref(import.meta.env.VITE_STATIC_IMAGE);
const { statusBarHeight, navHeight } = systemInfo();
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const barAlbright = ref(0);
const query = ref(null);
const pageInfo = ref<{ thisPage: number; title: string; type: string; btnTitle?: string }>({
	thisPage: -1,
	title: '暂无数据',
	type: 'btn',
	btnTitle: '重试',
});
const paperDetailsInfo = ref(null);
const current = ref(1);
const answerTime = ref(0);
const interval = ref(null);

onLoad(options => {
	console.log(options);
	if (!userInfo.value.student_id) {
		// 分享或者进入未登录
		pageInfo.value = {
			thisPage: 0,
			type: 'btn',
			title: '还没有登录',
			btnTitle: '登录',
		};
		uni.hideShareMenu({ hideShareItems: ['qq', 'qzone'] });
		return;
	}
	// 试卷 id
	// 计划 plan_id
	if (options.id) {
		query.value = options;
	} else {
		pageInfo.value = {
			thisPage: 0,
			title: '查询异常',
			type: 'msg',
		};
	}
});

onShow(() => {
	barAlbright.value = navHeight + statusBarHeight;
	if (query.value.id) {
		getInfo();
	}
});

onHide(() => {
	if (interval.value) {
		clearInterval(interval.value);
	}
});

const getInfo = async () => {
	uni.showLoading({
		title: '加载中...',
	});
	try {
		const res = await getPaperInfo({
			student_id: userInfo.value.student_id,
			paper_id: query.value.id,
			plan_id: query.value.plan_id || 0,
		});
		uni.hideLoading();
		if (res.status_code === 200 && res.data) {
			pageInfo.value.thisPage = 1;
			if (res.data.qtrunk.length) {
				res.data.qtrunk.forEach(item => {
					item.answer = '';
				});
			}
			interval.value = setInterval(() => {
				answerTime.value++;
			}, 1000);
			paperDetailsInfo.value = res.data;
		} else {
			uni.showToast({
				icon: 'none',
				title: res.status_code !== 200 ? res.message : '查询异常,请重试',
			});
			pageInfo.value = {
				thisPage: 0,
				title: res.status_code !== 200 ? res.message : '查询异常,请重试',
				type: 'btn',
			};
		}
	} catch (error) {
		uni.hideLoading();
		pageInfo.value = {
			thisPage: 0,
			title: '查询异常,请重试',
			type: 'btn',
		};
		uni.showToast({
			icon: 'none',
			title: '查询异常,请重试',
		});
	}
};

const retry = () => {
	if (!userInfo.value.student_id) {
		// 分享或者进入未登录
		toAuthPage({}, { type: 'redirectTo', url: '/pages/index/index' });
		return;
	}
	getInfo();
};

const getAnswer = arr => {
	if (arr.length) {
		paperDetailsInfo.value.qtrunk = arr;
	}
};

const prev = () => {
	current.value--;
};
const next = () => {
	current.value++;
};

const submit = async () => {
	// const flag = paperDetailsInfo.value.qtrunk.filter(item => item.answer.length === 0);
	// if (flag.length) {
	// 	uni.showToast({
	// 		icon: 'none',
	// 		title: '请完成测练',
	// 	});
	// 	const { master_code_crc32 } = flag[0];
	// 	const index = paperDetailsInfo.value.qtrunk.findIndex(
	// 		item => item.master_code_crc32 === master_code_crc32,
	// 	);
	// 	current.value = index !== -1 ? index + 1 : 1;
	// 	return;
	// }
	uni.showLoading({
		title: '提交中...',
	});
	try {
		const exam_answer = paperDetailsInfo.value.qtrunk.map(item => {
			return {
				master_code_crc32: item.master_code_crc32,
				answer: item.answer || '',
				right_answer: item.right_answer,
			};
		});
		clearInterval(interval.value);
		const res = await commitPaperInfo({
			student_id: userInfo.value.student_id,
			paper_id: Number(query.value.id),
			plan_id: query.value.plan_id ? Number(query.value.plan_id) : 0,
			answer_time: answerTime.value,
			exam_answer: JSON.stringify(exam_answer),
			code: paperDetailsInfo.value.code,
		});
		uni.hideLoading();
		if (res.status_code === 200 && res.data.exam_anser_id) {
			uni.showToast({
				icon: 'none',
				title: '提交完成',
			});
			uni.redirectTo({
				url: `/pages-book/exercise/details/index?answer_id=${res.data.exam_anser_id}`,
			});
		} else {
			interval.value = setInterval(() => {
				answerTime.value++;
			}, 1000);
			uni.showToast({
				icon: 'none',
				title: res.status_code !== 200 ? res.message : '提交失败',
			});
		}
	} catch (error) {
		interval.value = setInterval(() => {
			answerTime.value++;
		}, 1000);
		uni.hideLoading();
		uni.showToast({
			icon: 'none',
			title: '提交失败',
		});
	}
};
</script>

<style lang="scss" scoped>
.page-exercise {
	.paper-item {
		box-shadow:
			0rpx 0rpx 3rpx 0rpx rgb(0 0 0 / 3%),
			0rpx 5rpx 21rpx 0rpx rgb(0 0 0 / 7%);
	}

	.paper-image {
		box-shadow:
			0rpx 0rpx 3rpx 0rpx rgb(0 0 0 / 3%),
			0rpx 5rpx 21rpx 0rpx rgb(0 0 0 / 7%);
	}
}
</style>
